import axios from 'axios'
import { useUserStore } from '@/stores'
const userStore = useUserStore()

import router from '@/router'

// 服务器基地址
const baseURL = 'https://big-event-vue-api-t.itheima.net'

const instance = axios.create({
  // 基地址
  baseURL,
  // 超时时间
  timeout: 10000
})

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    console.log('请求正常')
    config.headers.Authorization = userStore.token
    return config
  },
  (error) => {
    console.log('请求错误')
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    console.log('响应正常')
    return response
  },
  (error) => {
    console.log('响应错误')
    if (!error.response) {
      ElMessage.error('无法连接到服务器！')
    } else {
      ElMessage.error(error.response.data.message)
    }
    router.push('/login')
    return Promise.reject(error)
  }
)

export default instance
export { baseURL }
